# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰无忧·重疾加倍保"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 17)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 重大疾病保赔
                "majorDisease": ["100000"],
                # 重大疾病医疗
                "seriousMedical": ["100000"],
                # 投保对象
                "payObject": ["子女"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 17)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 重大疾病保赔
                "majorDisease": ["250000"],
                # 重大疾病医疗
                "seriousMedical": ["250000"],
                # 投保对象
                "payObject": ["子女"]

            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(18, 60)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 重大疾病保赔
                "majorDisease": ["100000"],
                # 重大疾病医疗
                "seriousMedical": ["100000"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]

            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(18, 60)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 重大疾病保赔
                "majorDisease": ["250000"],
                # 重大疾病医疗
                "seriousMedical": ["250000"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["expire"], plan[k]["payType"],
                             plan[k]["majorDisease"], plan[k]["seriousMedical"], plan[k]["payObject"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                ))

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["payObject"] == "子女":
            data = {"calculateData": {"insuredInfo": [
                {"calinsuredRelationship": "40", "calinsuredBirth": "2002-10-02",
                 "calinsuredGender": "1" if dt["gender"] == "M" else "2",
                 "minimum": "0", "maximum": "59", "planAgeMax": "59", "planAgeMin": "0"}], "calinsuredPeriod": "Y1",
                "calstartDate": "2020-03-07 00:00:00", "calinsuredAge": dt["year"], "planLiabilityList": [
                    {"liabilityId": "1020001", "amount": dt["majorDisease"], "liabilityName": "重疾给付保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"},
                    {"liabilityId": "1020002", "amount": dt["majorDisease"], "liabilityName": "重疾医疗保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"}], "liabilityContents": [
                    {"liabilityId": "1020001", "amount": dt["majorDisease"], "liabilityName": "重疾给付保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"},
                    {"liabilityId": "1020002", "amount": dt["majorDisease"], "liabilityName": "重疾医疗保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"}], "planId": "1020A00601"},
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1235762513907187712",
                                 "applicationToken": "76ea6d63a8e508f9d1957bffeb36f4e6",
                                 "workqueueId": "1098473432023416832", "channelId": "3", "platformId": "pc",
                                 "referId": ""}}
        else:

            data = {"calculateData": {"insuredInfo": [
                {"calinsuredRelationship": "50", "calinsuredBirth": "2000-10-02", "calinsuredGender": "1" if dt["gender"]=="M" else "2",
                 "minimum": "0", "maximum": "59", "planAgeMax": "49", "planAgeMin": "0"}], "calinsuredPeriod": "Y1",
                                      "calstartDate": "2020-03-07 00:00:00", "calinsuredAge": dt["year"], "planLiabilityList": [
                    {"liabilityId": "1020001", "amount": dt["majorDisease"], "liabilityName": "重疾给付保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"},
                    {"liabilityId": "1020002", "amount": dt["majorDisease"], "liabilityName": "重疾医疗保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"}], "liabilityContents": [
                    {"liabilityId": "1020001", "amount": dt["majorDisease"], "liabilityName": "重疾给付保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"},
                    {"liabilityId": "1020002", "amount": dt["majorDisease"], "liabilityName": "重疾医疗保险金",
                     "liabilityAmount": ""+str(int(int(dt["seriousMedical"])/10000))+"万"}], "planId": "1020A00601"},
                    "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1235762513907187712",
                                     "applicationToken": "76ea6d63a8e508f9d1957bffeb36f4e6",
                                     "workqueueId": "1098473432023416832", "channelId": "3", "platformId": "pc",
                                     "referId": ""}}

        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "保费试算成功" in r.text:
            price = Helper.decimalParse(r.json()["data"]["sumPremium"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格数据更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
